require 'digest/sha1'

class WebsiteUser < ActiveRecord::Base
  
  validates_presence_of :email, :nickname
  validates_format_of :email, :with => /\A[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))\Z/i
  validates_length_of :password, :in => 6..20, :if => :validate_password?
  validates_confirmation_of :password

  def validate_password?
    @new_password
  end
  
  def password
    read_attribute(:password)
  end
  
  def password=(password)
    write_attribute(:password, password)
    write_attribute(:encrypted_password, self::class.encrypt(password)) unless password.blank?
    @new_password = !password.blank?
  end
  
  def new_random_password
    password = self::class.random_password
    write_attribute(:password, password)
    write_attribute(:encrypted_password, self::class.encrypt(password)) unless password.blank?
    @new_password = true
    save!
    UserMailer.deliver_password_email(self)
  end
  
  # Class methods
  
  def self.authenticate(email, password)
    return if password.blank?
    customer = find(:first, :select => "id", :conditions => ["email = ? and encrypted_password = ? and active = true and (end_date IS NULL or end_date > NOW())", email, self.encrypt(password)])
#    customer = find(:first, :select => "id", :conditions => { :email => email, :encrypted_password => self.encrypt(password), :active => true })
#    customer = find_by_email_and_encrypted_password(email, self.encrypt(password), :select => "id")
    customer.id unless customer.nil?
  end
  
  def self.encrypt(password)
    Digest::SHA1.hexdigest("#{SALT}--#{password}--")[0..39]
  end
  
  def self.random_password(len = 8)
    chars = ("a".."z").to_a + ("0".."9").to_a
    chars.delete("i")
    chars.delete("1")
    chars.delete("l")
    chars.delete("o")
    chars.delete("0")
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
    return newpass
  end
  
end
